<template>
  <div class="login-root">
    <div class="login-container">
      <img class="login-img" src="../../static/images/user.png" />
      <button
        v-if="buttonVisible"
        open-type="getUserInfo"
        @getuserinfo="bindGetUserInfo"
        @click="onSubscriput"
      >
        获取权限
      </button>
    </div>
    <p class="login-info">请先登录再进行后续操作</p>
  </div>
</template>
<script>
import wxApi from "@/api/wx_api";

export default {
  data() {
    return {
      buttonVisible: false,
    };
  },
  mounted() {
    const self = this;
    wx.login({
      success(res) {
        if (res.code) {
          self.code = res.code;
          self.wxGetUserInfo(res.code);
        }
      },
    });
  },
  methods: {
    wxGetUserInfo(code) {
      const self = this;
      wx.getUserInfo({
        withCredentials: true,
        success(res) {
          let { encryptedData, userInfo, iv } = res;
          self.$http
            .post(wxApi.wxLogin, {
              code,
              encryptedData,
              iv,
            })
            .then((res) => {
              console.log(userInfo);
              console.log(self.$store.state.user);
              console.log(`后台交互拿回数据:`, res);
              // 获取到后台重写的session数据，可以通过vuex做本地保存
              self.$store.commit("saveUser", res);
              if (res.realName === undefined || res.realName === "") {
                self.$store.commit("saveShowLandscape", false);
              }
              self.$router.go(-1);
            })
            .catch((err) => {
              console.log(`自动请求api失败 err:`, err);
            });
        },
        fail(err) {
          console.log("自动wx.getUserInfo失败:", err);
          // 显示主动授权的button
          self.buttonVisible = true;
        },
      });
    },
    onSubscriput() {
      // wx.requestSubscribeMessage({
      //   tmplIds: ["Liybyf6Oik96Wgr3DPgxX6DZENh5oK9twbJtHYSsZ3I"],
      //   success(res) {
      //     console.log(res);
      //   }
      // });
    },
    bindGetUserInfo(e) {
      // console.log('回调事件后触发')
      const self = this;
      if (e.mp.detail.userInfo) {
        console.log("用户按了允许授权按钮");
        let { encryptedData, userInfo, iv } = e.mp.detail;
        self.$http
          .post(wxApi.wxLogin, {
            // 这里的code就是通过wx.login()获取的
            code: self.code,
            encryptedData,
            iv,
          })
          .then((res) => {
            console.log(`后台交互拿回数据:`, res);
            // 获取到后台重写的session数据，可以通过vuex做本地保存
            self.$store.commit("saveUser", res);
            self.$router.go(-1);
            // self.$router.push({ path: '/pages/center', reLaunch: true });
          })
          .catch((err) => {
            console.log(`api请求出错:`, err);
          });
      } else {
        //用户按了拒绝按钮
        console.log("用户按了拒绝按钮");
      }
    },
  },
};
</script>

<style scoped lang="less">
.login-root {
  height: 60vh;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .login-container {
    box-sizing: border-box;
    padding-top: -20px;
    text-align: center;
    .login-img {
      width: 120px;
      height: 120px;
    }
    .login-btn {
      width: 100%;
      margin-top: 20px;
      display: block;
    }
  }
  .login-info {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0;
    left: 0;
  }
}
</style>